package com.burger.counter.servlets;

import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.burger.counter.beans.Region;
import com.burger.counter.beans.ShoppingCart;
import com.burger.counter.beans.User;
import com.burger.counter.business.RegionBusiness;
import com.burger.counter.business.UserBusiness;


public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
   
    public LoginServlet() {
        super();
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {		
		doPost(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {		
		System.out.println("i am in loginservlet");
		int result=1;
		RequestDispatcher dispatcher;
		UserBusiness userBI = new UserBusiness();
		
		HttpSession session = request.getSession(true); 
		String email = request.getParameter("email");
		String pass = request.getParameter("password");
		if(!email.equals("") && !pass.equals("")){
		try {
			result = userBI.checkPassword(email,pass);
			System.out.println("regionid"+ result);
		} 
		catch (Exception e) {
			e.printStackTrace();
		}
		}
		if(result != 1){
		
			User[] userDetails = userBI.getUserDetails(email);
			if(userDetails != null)
			{
				session.setAttribute("UserId", userDetails[0].getUserId());
				session.setAttribute("Email", email);
			}
			RegionBusiness regionBI=new RegionBusiness();
			Region region[];
			Double tax=0.0;
			try {
				region=regionBI.getTaxDetails(String.valueOf(result));
				tax=region[0].getTax();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		session.setAttribute("RegionId", result);
		session.setAttribute("Tax",tax);
		session.setAttribute("UserEmailId", email);
		int userId = userBI.getUserId(email);
		session.setAttribute("UserId", userId);
		ShoppingCart cart=(ShoppingCart)session.getAttribute("Cart");
		
		dispatcher = getServletContext().getRequestDispatcher("/main.jsp");
		dispatcher.forward(request, response);
	
		}
		else{
		request.setAttribute("errorMessage", "Invalid Username or Password"); 
		dispatcher = getServletContext().getRequestDispatcher("/welcome.jsp");
		dispatcher.forward(request, response);
		}
			
		
		
		
	}

}
